package com.atguigu.tingshu.user.service.impl;

import cn.binarywang.wx.miniapp.api.WxMaService;
import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.common.rabbit.constant.MqConst;
import com.atguigu.tingshu.common.rabbit.service.RabbitService;
import com.atguigu.tingshu.model.user.UserInfo;
import com.atguigu.tingshu.user.mapper.UserInfoMapper;
import com.atguigu.tingshu.user.service.UserInfoService;
import com.atguigu.tingshu.vo.user.UserInfoVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
@SuppressWarnings({"all"})
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private WxMaService wxMaService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RabbitService rabbitService;


    @Override
    public HashMap<String, Object> wxLogin(String code) {
        //	通过code 换取 openId; 表示微信的唯一标识
        String openid = null;
        try {
            openid = wxMaService.jsCode2SessionInfo(code).getOpenid();
        } catch (WxErrorException e) {
            throw new RuntimeException(e);
        }
        //	通过openid 查询用户信息是否存在
        UserInfo userInfo = userInfoMapper.selectOne(new LambdaQueryWrapper<UserInfo>().eq(UserInfo::getWxOpenId, openid));
        //	判断
        if (null == userInfo) {
            //	用户信息不存在,
            userInfo = new UserInfo();
            //	赋值：
            userInfo.setWxOpenId(openid);
            userInfo.setNickname("听友:" + System.currentTimeMillis());
            userInfo.setAvatarUrl("https://oss.aliyuncs.com/aliyun_id_photo_bucket/default_handsome.jpg");
            //	保存用户信息
            userInfoMapper.insert(userInfo);
            //  初始化账户金额： 听书项目: user_account
            //  第一种： 实现远程调用：feignClient  第二种：发送消息的形式：异步
            rabbitService.sendMessage(MqConst.EXCHANGE_USER,MqConst.ROUTING_USER_REGISTER,userInfo.getId());
        }
        //  声明一个token
        String token = UUID.randomUUID().toString().replaceAll("-", "");
        //	不为空 直接存储数据到缓存
        String userLoginKey = RedisConstant.USER_LOGIN_KEY_PREFIX + token;
        //  存储数据
        this.redisTemplate.opsForValue().set(userLoginKey, userInfo, RedisConstant.USER_LOGIN_KEY_TIMEOUT, TimeUnit.SECONDS);
        HashMap<String, Object> map = new HashMap<>();
        map.put("token", token);
        //  返回数据
        return map;
    }

    @Override
    public UserInfoVo getUserInfo(Long userId) {
        //  查询数据
        UserInfo userInfo = this.getById(userId);
        //  创建一个对象
        UserInfoVo userInfoVo = new UserInfoVo();
        //  属性拷贝：
        BeanUtils.copyProperties(userInfo,userInfoVo);
        return userInfoVo;
    }

    @Override
    public void updateUserById(Long userId, UserInfoVo userInfoVo) {
        //  根据用户Id 修改用户昵称， 以及url地址; 保证redis 与 mysql 数据一致性; canal 后续完成
        //  update user_info set nickname = ? and avatar_url=? where user_id = ? and is_deleted = 0;
        UserInfo userInfo = new UserInfo();
        userInfo.setId(userId);
        userInfo.setNickname(userInfoVo.getNickname());
        userInfo.setAvatarUrl(userInfoVo.getAvatarUrl());
        this.userInfoMapper.updateById(userInfo);

    }
}
